package persistent

import (
	"context"
	"time"

	"gorm.io/gorm"
)

const TableNameNodeReviewerTask = "node_reviewer_task"

type NodeReviewerTaskClient struct {
	db *gorm.DB `name:"saas_db"`
}

func NewNodeReviewerTaskClient(db *gorm.DB) *NodeReviewerTaskClient {
	return &NodeReviewerTaskClient{db: db}
}

func (w *NodeReviewerTaskClient) BatchCreateTX(ctx context.Context, tx *gorm.DB, po ...NodeReviewerTask) (err error) {
	return tx.WithContext(ctx).Create(&po).Error
}

func (w *NodeReviewerTaskClient) QueryReviewerTaskByID(ctx context.Context, id string) (result NodeReviewerTask, err error) {
	return result, w.db.WithContext(ctx).Take(&result, "id = ?", id).Error
}

func (w *NodeReviewerTaskClient) QueryReviewerTaskByIDTX(ctx context.Context, id string, tx *gorm.DB) (result NodeReviewerTask, err error) {
	return result, tx.WithContext(ctx).Take(&result, "id = ?", id).Error
}

func (w *NodeReviewerTaskClient) QueryByNodeIDTX(ctx context.Context, nodeID string, tx *gorm.DB) (result []NodeReviewerTask, err error) {
	err = tx.WithContext(ctx).Where("node_id = ?", nodeID).Find(&result).Error
	return result, err
}

func (w *NodeReviewerTaskClient) UpdateTX(ctx context.Context, po NodeReviewerTask, tx *gorm.DB) (err error) {
	return tx.WithContext(ctx).Model(&po).Updates(&po).Error
}

func (w *NodeReviewerTaskClient) UpdateByCondTX(ctx context.Context, cond NodeReviewerTask, po NodeReviewerTask, tx *gorm.DB) (err error) {
	return tx.WithContext(ctx).
		Model(&NodeReviewerTask{}).
		Where(&cond).
		Updates(&po).Error
}

func (w *NodeReviewerTaskClient) DeleteNodeReviewerTaskByCondTX(ctx context.Context, nodeIDs []string, tx *gorm.DB) (err error) {
	return tx.WithContext(ctx).
		Where("node_id in ?", nodeIDs).
		Delete(&NodeReviewerTask{}).Error
}

type NodeReviewerTask struct {
	ID         string `gorm:"column:id;type:varchar(64);primaryKey;comment:Snowflake ID | 全局唯一ID"`
	NodeID     string `gorm:"column:node_id;type:varchar(64)"`
	ReviewerID string `gorm:"column:reviewer_id;type:varchar(64)"`
	Comment    string `gorm:"column:comment;type:json"`
	Status     int    `gorm:"type:tinyint(5);not null;column:status;"`

	CreatedAt time.Time `gorm:"column:created_at;comment:Created Time | 创建时间" json:"created_at"`
	UpdatedAt time.Time `gorm:"column:updated_at;comment:Updated Time | 更新时间" json:"updated_at"`
}

func (w NodeReviewerTask) TableName() string {
	return TableNameNodeReviewerTask
}
